<?php
class Rsabak
{
    public $publicKey = '-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAvYLdLkawzXJkpy92+mc8
yDPcGPDWYOYSQ4yssfLmW2ogUGkBNthGM846Cc4HxU/ixkBp+pObleusVMeYmIrz
0MDBf4NlT97SWhipBXI1gvd7W6ZZvPx1EI41g7+yCOdlOgNgns1htEl57803ICVy
UCuWQFABqo/FBUHmFqhKHg+BaRrAjcOUn6F8oo09QBFrwD/Oo0hW7MrkA5TRBwMN
UhV3QoCPS9uHNpB7yanJyyUaO10c+LLE/LA/GUzrfEFieQQ/p/21/xnxhp6T27IS
XhG3w6s0t/Oger7BDSQhrKc5f+zbJGjhxYjSBXG54fH1ADA7aSWUuFfmZRyIrHFV
MwIDAQAB
-----END PUBLIC KEY-----';

    public $privateKey = '-----BEGIN PRIVATE KEY-----
MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQC9gt0uRrDNcmSn
L3b6ZzzIM9wY8NZg5hJDjKyx8uZbaiBQaQE22EYzzjoJzgfFT+LGQGn6k5uV66xU
x5iYivPQwMF/g2VP3tJaGKkFcjWC93tbplm8/HUQjjWDv7II52U6A2CezWG0SXnv
zTcgJXJQK5ZAUAGqj8UFQeYWqEoeD4FpGsCNw5SfoXyijT1AEWvAP86jSFbsyuQD
lNEHAw1SFXdCgI9L24c2kHvJqcnLJRo7XRz4ssT8sD8ZTOt8QWJ5BD+n/bX/GfGG
npPbshJeEbfDqzS386B6vsENJCGspzl/7NskaOHFiNIFcbnh8fUAMDtpJZS4V+Zl
HIiscVUzAgMBAAECggEAGwu3FyidiOR/euCqQThEk2nbSm/smG2dQ6iq6MZ6m6c8
r10dAD/DXRdcbxPJRh6Nha+hsFIqjS3SLVNC8to5y5wGwXT2G3z4VkVYsd9HxcYe
A8ls2yzIZDF3b7MG7IBhkPL0chVrkTg/P7rw2BSgCNL/oXQJmNblzkdGWAtycHGU
+h2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KEY-----';
    
    public function __construct()
    {
//        // 生成新的私钥和公钥对
//        $resource = openssl_pkey_new();
//        openssl_pkey_export($resource, $this->privateKey);
//        $detail = openssl_pkey_get_details($resource);
//        $this->publicKey = $detail['key'];
    }

    public function publicEncrypt($data, $publicKey)
    {
        openssl_public_encrypt($data, $encrypted, $publicKey);
        return $encrypted;
    }

    public function publicDecrypt($data, $publicKey)
    {
        openssl_public_decrypt($data, $decrypted, $publicKey);
        return $decrypted;
    }

    public function privateEncrypt($data, $privateKey)
    {
        openssl_private_encrypt($data, $encrypted, $privateKey);
        return $encrypted;
    }

    public function privateDecrypt($data, $privateKey)
    {
        openssl_private_decrypt($data, $decrypted, $privateKey);
        return $decrypted;
    }
}


$rsa = new Rsabak();
echo "公钥：\n", $rsa->publicKey, "\n";
echo "私钥：\n", $rsa->privateKey, "\n";

// 使用公钥加密
$str = $rsa->publicEncrypt('hello', $rsa->publicKey);
// 这里使用base64是为了不出现乱码，默认加密出来的值有乱码
$str = base64_encode($str);
echo "公钥加密（base64处理过）：\n", $str, "\n";
$str = base64_decode($str);
$pubstr = $rsa->publicDecrypt($str, $rsa->publicKey);
echo "公钥解密：\n", $pubstr, "\n";
$privstr = $rsa->privateDecrypt($str, $rsa->privateKey);
echo "私钥解密：\n", $privstr, "\n";

// 使用私钥加密
$str = $rsa->privateEncrypt('world', $rsa->privateKey);
// 这里使用base64是为了不出现乱码，默认加密出来的值有乱码
$str = base64_encode($str);
echo "私钥加密（base64处理过）：\n", $str, "\n";
$str = base64_decode($str);
$pubstr = $rsa->publicDecrypt($str, $rsa->publicKey);
echo "公钥解密：\n", $pubstr, "\n";
$privstr = $rsa->privateDecrypt($str, $rsa->privateKey);
echo "私钥解密：\n", $privstr, "\n";